<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

<!--      <el-form-item label="标题" prop="title">-->
<!--        <el-input-->
<!--          v-model="queryParams.title"-->
<!--          placeholder="请输入标题"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label="宠物类型" prop="classId">
        <el-select v-model="queryParams.petType" clearable placeholder="请选择宠物类型">
          <el-option
            v-for="item in petTypeList"
            :key="item.id"
            :label="item.petType"
            :value="item.petType"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['petSys:promAdoption:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-user"
          size="mini"
          @click="handleQuery(1)"
          v-hasPermi="['petSys:promAdoption:remove']"
        >我的发布</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  v-loading="loading" :data="promAdoptionList" @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="标题">
              <span style="font-weight: bolder">{{ props.row.title }}</span>
            </el-form-item>
            <el-form-item label="发布者">
              <span>{{ props.row.nickName }}</span>
            </el-form-item>
            <el-form-item label="描述">
              <span v-html="props.row.content"></span>
            </el-form-item>
            <el-form-item label="图片">

              <div style="display: flex;">
                <div v-for="(item) in props.row.imgUrlList" style="margin: 10px">
                  <img :src="item"  @click="picture(item)"   :width="100" :height="100">
                </div>
              </div>
            </el-form-item>
<!--            <el-form-item label="是否被领养">-->
<!--              <span>{{ props.row.petType }}</span>-->
<!--            </el-form-item>-->
          </el-form>
        </template>
      </el-table-column>
<!--      发布者名字-->
      <el-table-column style="font-weight : bold" label="标题" align="center" prop="title" />
      <el-table-column label="用户名" align="center" prop="nickName" />
      <el-table-column label="宠物类型" align="center" prop="petType" />
      <el-table-column label="发布时间" align="center" prop="promTime" width="180">
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.row.promTime }}</span>-->
<!--        </template>-->
      </el-table-column>

<!--      <el-table-column label="是否被领养" align="center" prop="isAdoption" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.promUserId!=userId"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="checkApply(scope.row)"
          >申领</el-button>
          <el-button
            v-if="scope.row.promUserId == userId"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['petSys:promAdoption:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改发布领养对话框 -->
    <el-dialog :title="title"  :visible.sync="open" width="800px" hei append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="宠物类型" prop="classId">
          <el-select v-model="form.petType" clearable placeholder="请选择宠物类型">
            <el-option
              v-for="item in petTypeList"
              :key="item.id"
              :label="item.petType"
              :value="item.petType"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="http://localhost:8080/petSys/promAdoption/adoptionUpload"
            :limit = "3"
            list-type="picture-card"
            :on-exceed="limitEvent"
            :headers="headers"
            :on-success="uploadSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :multiple="true"
            :on-progress="handleProgress"
            >
<!--            <el-button slot="trigger" size="small" type="primary">选取图片</el-button>-->
            <i class="el-icon-plus"></i>
<!--            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 申请 -->
    <el-dialog title="申请领养"  :visible.sync="applyOpen" width="800px" hei append-to-body>
      <el-form ref="applyFrom" :model="applyFrom"  label-width="80px">

        <el-form-item label="领养缘由" prop="applyReason">
          <el-input v-model="applyFrom.applyReason" placeholder="请输入领养缘由" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitApplyAdoption">确 定</el-button>
        <el-button @click="applyCancel">取 消</el-button>
      </div>
    </el-dialog>
    <div class="image-preview">
      <el-image style="width: 0; height: 0" ref="previewImg" :src="url" :preview-src-list="srcList">
      </el-image>
    </div>

  </div>
</template>

<script>
import {
  listPromAdoption,
  getPromAdoption,
  delPromAdoption,
  addPromAdoption,
  updatePromAdoption, getBaseUrl, deleteAdopImg,addApplyAdoption
} from "@/api/petSys/promAdoption";
import {listTypeList} from "@/api/petSys/otherComm";
import { getToken } from "@/utils/auth";


export default {

  name: "PromAdoption",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发布领养表格数据
      promAdoptionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      applyOpen:false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        promUserId: null,
        promTime: null,
        title: null,
        content: null,
        imgUrl: null,
        petType: null,
      },
      // 表单参数
      form: {},
      applyFrom: {},
      // 表单校验
      rules: {
      },

      dialogImageUrl: '',
      dialogVisible: false,
      // disabled: false,
      headers: { Authorization: "Bearer " + getToken() },
      fileUrlList: [],
      petTypeList:[],
      imgUrlList:[],
      bastUrl:"",
      userId:0,
      url:"",
      srcList:[]
    };
  },
  created() {
    getBaseUrl().then(response => {
      this.bastUrl = response;
    });
    this.getList();
    this.getPetTypeList();
  },
  mounted() {
    this.userId = this.$store.state.user.id;
  },
  methods: {
    getPetTypeList(){
      listTypeList().then(response => {
        this.petTypeList = response.rows;
      });
    },
    /** 查询发布领养列表 */
    getList() {
      this.loading = true;
      listPromAdoption(this.queryParams).then(response => {
        this.promAdoptionList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.promAdoptionList.forEach(item=>{
          if(item.imgUrl != null){
            item.imgUrlList = item.imgUrl.split(";");
            item.imgUrlList.splice(item.imgUrlList.length-1,1)
            for(var i = 0 ;i<item.imgUrlList.length;i++){
              item.imgUrlList[i]= item.imgUrlList[i].replace(/\\/g,"/")
              item.imgUrlList[i]= "/"+item.imgUrlList[i]

              console.log(item.imgUrlList[i]);
            }

          }
        })

        console.log(this.promAdoptionList);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    applyCancel() {
      this.applyOpen = false;
      this.applyReset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        promUserId: null,
        promTime: null,
        title: null,
        content: null,
        imgUrl: null,
        petType: null,
        isAdoption: null,
        updateTime: null
      };
      this.resetForm("form");
      this.fileUrlList = [];
    },
    applyReset(){
      this.applyFrom = {
        adoptionId : null,
        applyReason : null,
        promUserId :null,
      };
    },
    /** 搜索按钮操作 */
    handleQuery(e) {
      this.queryParams.pageNum = 1;
      if(e==1){
        this.queryParams.promUserId = this.userId;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.petType= null;
      this.queryParams.promUserId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发布领养";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPromAdoption(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发布领养";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.imgUrl=""
        this.fileUrlList.forEach(item => {
          this.form.imgUrl += item + ";"
        })
        this.$refs.upload.clearFiles();
        if (valid) {
          if (this.form.id != null) {
            updatePromAdoption(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPromAdoption(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除发布领养编号为"' + ids + '"的数据项？').then(function() {
        return delPromAdoption(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    checkApply(row){
      console.log(row)

      this.applyReset();
      this.applyOpen =  true;
      this.applyFrom.adoptionId =row.id
      this.applyFrom.applyUserId =this.userId
      this.applyFrom.promUserId =row.promUserId
    },
    /**
     * 申请领养宠物
     * @param row
     */
    submitApplyAdoption(row){

      addApplyAdoption(this.applyFrom).then(response => {
        this.$modal.msgSuccess("申领成功");

      })


      this.applyOpen =  false;
    },


    submitUpload() {
      this.$refs.upload.submit();
    },
    uploadSuccess(response, file, fileList) {

      console.log(response)

      this.fileUrlList.push(response.data);


    },
    limitEvent(){
      this.$modal.alertWarning("最大只能选择三张图片")
    },
    handleRemove(file, fileList){
      this.fileUrlList.splice(this.fileUrlList.indexOf(file.response.data), 1);
      deleteAdopImg(file.response.data).then(response => {
        console.log(response)
      })

    },

    handlePictureCardPreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleProgress(event, file, fileList){


      if (file.raw.type.indexOf("image/") == -1) {
        this.$refs.upload.abort(file);
        fileList.splice(fileList.indexOf(file),1);
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      }

    },
    picture(value) {
      console.log(value)
      this.srcList = [value]
      this.viewBigPicture()
    },
    viewBigPicture() {
      this.$refs.previewImg.showViewer = true
    }



  }
};
</script>
<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 40%;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.el-upload-list__item-thumbnail {
  width: 100%;
  height: 100%; /* 或者指定一个固定高度 */
  object-fit: cover; /* 这将使图片缩放以适应内容区域，同时保持其纵横比 */
}
div:has(.el-upload-list__item-thumbnail) {
  /* 在这里放置您想要应用到父级div的样式 */
  height: 100%; /* 或者指定一个固定高度 */
}

.dialog-footer {
  position:absolute;
  right: 40px;
  bottom: 30px;
}
</style>
